from flask import Flask, request, render_template, send_from_directory
from mdict_utils.reader import MDX
#from mdict_utils.reader import MDD
import os

app = Flask(__name__)
sound_FOLDER = "static/sound"
os.makedirs(sound_FOLDER, exist_ok=True)


# 加载词典 .mdx
mdx = MDX("dict/牛津高阶8简体.mdx")
keys = list(mdx.keys())

def query_mdx(mdx_obj, word):
    """ 安全查询MDX词典内容的函数 """
    for k, value in mdx_obj.items():
        key=k.decode("utf-8")
        if key == word:
            return(value.decode("utf-8"))
    return None



# 加载 .mdd 资源
#mdd = MDD("dict/牛津高阶8简体.mdd")
#mdd_data = dict(mdd.items())

def find_resource(word):
    results = {"images": [], "audio": []}
    for key in mdd_data.keys():
        decoded_key = key.decode("utf-8", errors="ignore").lower()
        decoded_key = decoded_key.replace("\\", "/") 
        if word in decoded_key:
            if decoded_key.endswith((".jpg", ".png")):
                results["images"].append((decoded_key ))
            elif decoded_key.endswith((".spx", ".mp3", ".ogg")):
                results["audio"].append((decoded_key))
    return results



def save_resource2(key, filename):
    path = os.path.join(sound_FOLDER, filename)
    # 如果不存在，就保存一份
    if not os.path.exists(path):
        with open(path, "wb") as f:
            #f.write(mdd_data[key])
            pass
    return f"/static/sound/{filename}"



# 静态资源
@app.route("/static/<path:filename>")
def downloader(filename):
    return send_from_directory("static", filename, as_attachment=False)
# 图片资源
@app.route("/pic/<path:filename>")
def downloader2(filename):
    return send_from_directory("static/images/pic/", filename, as_attachment=False)
# 图片资源
@app.route("/thumb/<path:filename>")
def downloader2B(filename):
    return send_from_directory("static/images/thumb/", filename, as_attachment=False)
@app.route("/uk_pron.png")
def downloader_a1():
    return send_from_directory("static/images/", "uk_pron.png", as_attachment=False)
@app.route("/us_pron.png")
def downloader_a2():
    return send_from_directory("static/images/", "us_pron.png", as_attachment=False)

@app.route("/O8C.css")
def downloader_css():
    return send_from_directory("dict/", "O8C.css", as_attachment=False)

# 声音资源
@app.route("/uk/<path:filename>")
def downloader3(filename):
    return send_from_directory("static/sound/uk/", filename, as_attachment=False)
@app.route("/us/<path:filename>")
def downloader3B(filename):
    return send_from_directory("static/sound/us/", filename, as_attachment=False)


@app.route("/", methods=["GET", "POST"])
def index():
    word = request.form.get("word", "").strip().lower()
    content = query_mdx(mdx, word)

    images, audios = [], []

    # 不再查找额外的图片和音频
    if word and 0:
        found = find_resource(word)
        images=found["images"]
        audios=found["audio"]
        #images = [save_resource(k, os.path.basename(name)) for k, name in found["images"]]
        #audios = [save_resource(k, os.path.basename(name)) for k, name in found["audio"]]

    # 转换资源链接
    if content:
        content = content.replace(
            "sound://", 
            "/static/sound/"
        )
    return render_template("index.html", word=word, content=content, images=images, audios=audios)

if __name__ == "__main__":
    # app.run(debug=True)
    app.run(host="0.0.0.0",port=8005, debug=True)

